package cn.org.july.weixin.controller;

import cn.org.july.weixin.common.constant.WxConstant;
import cn.org.july.weixin.common.utils.HttpClientUtils;
import cn.org.july.weixin.service.config.WxConfig;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 获取用户信息服务
 *
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-09-12 13:45
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/wx/user")
public class OauthUserInfoController {

    @Resource
    private WxConfig config;

    @GetMapping("/getUser/{code}")
    public String userInfo(@PathVariable("code") String code) throws IOException {
        String appId = config.getAppId();
        String appSecret = config.getAppSecret();
        String url = WxConstant.OAUTH_GET_AT.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
        String accessToken = HttpClientUtils.get(url);
        JSONObject jsonObject = JSONObject.parseObject(accessToken);
        String errCode = jsonObject.getString("errcode");
        if (StringUtils.isNotEmpty(errCode)) {
            log.error("getUser is error , message is [{}]", accessToken);
            return accessToken;
        }
        String at = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        log.info("userInfo code = [{}] , access_token = [{}] , openId = [{}]", code, at, openId);
        url = WxConstant.OAUTH_USER_INFO.replace("ACCESS_TOKEN", at).replace("OPENID", openId);
        String userInfoStr = HttpClientUtils.get(url);
        log.info("userInfo is [{}]", userInfoStr);
        return userInfoStr;
    }

}
